package cn.com.spic.demo.controller;

import cn.com.spic.demo.api.*;
import cn.com.spic.demo.dto.*;
import cn.com.spic.demo.utils.ExcelExportUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cpipec.demo.spi.EOSServerRestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 集团公司对标提升工作月度报告-上报稿
 */
@RestController
@RequestMapping("/groupcompanysbg")
public class GroupCompany_sbgController {
    @Autowired
    private ActionProjectService actionProjectService;
    @Autowired
    private ProgressReportService progressReportService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EOSServerRestClient eosServerRestClient;
    @Value("${file.address}")
    private String fileAddress;
    @Autowired
    private SpecialProjectService specialProjectService;
    @Autowired
    private ReportService reportService;
    @Autowired
    private OrganizationService organizationService;
    /**
     * 月度报告保存
     * @param request
     */
    @GetMapping("/saveReport")
    public String saveReport(HttpServletRequest request) throws ParseException {
       try{
           Calendar cal = Calendar.getInstance();
           String spicFirstDeptId = request.getParameter("spicFirstDeptId");
           String yyfx = request.getParameter("yyfx");
           String zfAndj = request.getParameter("zfAndjy");
           String jybgjcs = request.getParameter("jybgjcs");
           String status = request.getParameter("status");
           ReportDTO reportDTO=new ReportDTO();
           Map<String,String> map=new HashMap<>();
           EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
           String submitMonth = null;
           String submitYear = String.valueOf(cal.get(Calendar.YEAR));
           int month = cal.get(Calendar.MONTH);
           if(month<=9){
               submitMonth = "0"+month;
           }else{
               submitMonth = String.valueOf(month);
           }
           if(month==0){
               submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
               submitMonth="12";
           }
           reportDTO.setType("3");
           reportDTO.setYyfx(yyfx);
           reportDTO.setZfAndjy(zfAndj);
           reportDTO.setJybgjcs(jybgjcs);
           reportDTO.setDeptid(spicFirstDeptId==null?employee.getOrgCode():spicFirstDeptId);
           reportDTO.setCreateor(employee.getCode());
           reportDTO.setSubmitYear(submitYear);
           reportDTO.setSubmitMonth(submitMonth);
           reportDTO.setStatus(status);
           map.put("submitYear",submitYear);
           map.put("submitMonth",submitMonth);
           map.put("deptid",spicFirstDeptId);
           map.put("type","3");
           ReportDTO reportDTO1=reportService.getReportByCondition(map);
           if(reportDTO1.getId()==null){
               reportService.insertReport(reportDTO);
           }else{
               reportService.updateReport(reportDTO);
           }

           return "保存成功";
       }catch (Exception e){
           e.printStackTrace();
       }
        return "保存失败，请重新保存！";
    }
    private String getUserCode(){
        JSON json = eosServerRestClient.getCurrentUser();
        JSONObject object = JSONObject.parseObject(json.toJSONString());
        return object.getString("username");
    }
    /**
     * 月度报告保存
     * @param request
     */
    @GetMapping("/exportWord")
    public String exportWord(HttpServletRequest request) throws ParseException {
        String base1=request.getParameter("base1");
        String base2=request.getParameter("base2");
        String base3=request.getParameter("base3");
        return "保存失败，请重新保存！";
    }



    /**
     * 计算时间差
     */
    private Long getDayNum(String day1,String day2) throws Exception {
        Date    a11 = new SimpleDateFormat("yyyy-MM-dd").parse(day1);
        Date    b11 = new SimpleDateFormat("yyyy-MM-dd").parse(day2);
        long dayNum = (a11.getTime()-b11.getTime())/(24*60*60*1000);
        return dayNum;
    }



    private static List<String> getMonthBetween(String minDate, String maxDate) throws Exception {
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }
    private static String subMonth(String date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dt = sdf.parse(date);

        Calendar rightNow = Calendar.getInstance();

        rightNow.setTime(dt);

        rightNow.add(Calendar.MONTH, -1);
        Date dt1 = rightNow.getTime();

        String reStr = sdf.format(dt1);

        return reStr;
    }
    /**
     * XX公司对标提升工作月度报告---累计完成进度
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/groupReportMonth_ljwcjd" )
    public List<ProgressReportDTO> groupReportMonth_ljwcjd(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        List<SpecialProjectDTO> specialProjectDTOS = specialProjectService.getAllSpecialProList();
        List<ProgressReportDTO> nineList=new ArrayList<ProgressReportDTO>();
        List<EchartDTO> echartDTOS = progressReportService.groupReportMonth_ljwcjd(map);
        Double sjwc=0.00;
        Double jhwc=0.00;
        Integer count=0;
        for(SpecialProjectDTO dto:specialProjectDTOS){
            ProgressReportDTO progressReportDTO=new ProgressReportDTO();
            for(EchartDTO echartDTO:echartDTOS){
                if(echartDTO.getJdxid().equals(dto.getId())){
                    sjwc+=Double.parseDouble(echartDTO.getSjwc());
                    jhwc+=Double.parseDouble(echartDTO.getJhwc());
                    count++;
                }
            }
            progressReportDTO.setSjwc(sjwc/count+"");
            progressReportDTO.setJhwc(jhwc/count+"");
            progressReportDTO.setJhwcl(sjwc/jhwc+"");
            progressReportDTO.setNineProjectName(dto.getSpecialProjectName());
            nineList.add(progressReportDTO);
        }
        return nineList;
    }
    /**
     * XX公司对标提升工作月度报告---当月完成进度
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/groupReportMonth_dywcjd" )
    public List<ProgressReportDTO> groupReportMonth_dywcjd(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String preSubmitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        String preSubmitYear = String.valueOf(cal.get(Calendar.YEAR));
        Map<String,String> map = new HashMap<>();
        Map<String,String> preMap = new HashMap<>();//查询上个月的填报数据
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
            preSubmitMonth = "0"+(month-1);
        }else{
            submitMonth = String.valueOf(month);
            preSubmitMonth = String.valueOf(month-1);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
            preSubmitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            preSubmitMonth="11";
        }
        if(month==1){
            preSubmitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            preSubmitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        preMap.put("endtime",subMonth(subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date()))));
        preMap.put("submitYear",preSubmitYear);
        preMap.put("submitMonth",preSubmitMonth);
        List<SpecialProjectDTO> specialProjectDTOS = specialProjectService.getAllSpecialProList();
        List<ProgressReportDTO> nineList=new ArrayList<ProgressReportDTO>();
        List<EchartDTO> echartDTOS = progressReportService.groupReportMonth_ljwcjd(map);//当前月填报数据
        List<EchartDTO> preechartDTOS = progressReportService.groupReportMonth_ljwcjd(preMap);//当前月上一个月填报数据
        for(SpecialProjectDTO dto:specialProjectDTOS){
            Double sjwc=0.0;
            Double jhwc=0.0;
            Integer count=0;
            ProgressReportDTO progressReportDTO=new ProgressReportDTO();
            for(EchartDTO echartDTO:echartDTOS){
                if(echartDTO.getJdxid().equals(dto.getId())){
                    count++;
                   if(preechartDTOS.size()<=0){
                       progressReportDTO.setSjwc(echartDTO.getSjwc());
                       progressReportDTO.setJhwc(echartDTO.getJhwc());
                       progressReportDTO.setJhwcl((Double.parseDouble(echartDTO.getSjwc()))/(Double.parseDouble(echartDTO.getJhwc()))+"");
                       progressReportDTO.setNineProjectName(echartDTO.getJdx());
                       continue;
                   }else{
                       for(EchartDTO preehartdto:preechartDTOS){
                           if(preehartdto.getActionid().equals(echartDTO.getActionid())){
                                sjwc+=(((Double.parseDouble(echartDTO.getSjwc()))-(Double.parseDouble(preehartdto.getSjwc()))));//填报月上一个月的实际完成进度减去填报月的实际完成进度
                               String starttime=echartDTO.getStarttime();
                               String endtime=echartDTO.getEndtime();
                               if((Double.parseDouble(preehartdto.getSjwc()))<(Double.parseDouble(preehartdto.getJhwc()))){//填报上一个月的实际完成进度小于计划完成进度
                                   jhwc+=1.0/(((getMonthDiff(sdf.parse(endtime),sdf.parse(starttime))+1)+((Double.parseDouble(preehartdto.getJhwc()))-Double.parseDouble(echartDTO.getJhwc()))));
                               }else{
                                   jhwc+=1.0/(((getMonthDiff(sdf.parse(endtime),sdf.parse(starttime))+1)));
                               }
                               continue;
                           }

                       }
                   }

                }

            }
            progressReportDTO.setSjwc(sjwc/count+"");
            progressReportDTO.setJhwc(jhwc/count+"");
            progressReportDTO.setJhwcl((sjwc/count)/(jhwc/count)+"");
            progressReportDTO.setNineProjectName(dto.getSpecialProjectName());
            nineList.add(progressReportDTO);
        }
//        for(ProgressReportDTO dto:nineList){
//            System.out.println(dto.getNineProjectName()+"==="+dto.getSjwc()+"===="+dto.getJhwc()+"===="+dto.getJhwcl());
//        }
        return nineList;
    }
    /**
     * XX专项对标提升工作月度报告--累计进度报告
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/getActionByZx_ljjd" )
    public List<EchartDTO> getActionByZx_ljjd(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        String jdxid = httpServletRequest.getParameter("jdxid");
        jdxid="1";
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        map.put("jdxid","1");
        List<EchartDTO> echartDTOS = progressReportService.getActionByZx(map);//某个对标领域的120专项
        List<ActionProejctDTO> actionProejctDTOS=actionProjectService.getAllAction();//全部的行动项
        List<EchartDTO> list=new ArrayList<>();
        for(ActionProejctDTO actionProejctDTO:actionProejctDTOS){
            if(actionProejctDTO.getLevel().equals("1")&&actionProejctDTO.getSpecialId().equals(jdxid)){
                EchartDTO echartDTO=new EchartDTO();
                Double sjwc=0.0;
                Double jhwc=0.0;
                int count=0;
                for(EchartDTO echartDTO1:echartDTOS){
                    if(echartDTO1.getLevel().equals("3")){//如果等于3代表是二级单位
                        for(ActionProejctDTO actionProejctDTO1:actionProejctDTOS){
                            String parentid[]=echartDTO1.getActionid().split(",");
                            for(String str:parentid){
                                if(str.equals(actionProejctDTO1.getId())){
                                    String parentProjectId=actionProejctDTO1.getParentProjectId();
                                    if(parentProjectId.equals(actionProejctDTO.getId())){
                                        sjwc+=Double.parseDouble(echartDTO1.getSjwc());
                                        jhwc+=Double.parseDouble(echartDTO1.getJhwc());
                                        count++;
                                    }
                                }
                            }
                        }
                    }else if(echartDTO1.getLevel().equals("2")){
                        String parentid[]=echartDTO1.getActionid().split(",");
                        for(String str:parentid){
                            if(str.equals(actionProejctDTO.getId())){
                                sjwc+=Double.parseDouble(echartDTO1.getSjwc());
                                jhwc+=Double.parseDouble(echartDTO1.getJhwc());
                                count++;
                            }
                        }
                    }

                }
                echartDTO.setJdx(actionProejctDTO.getActionProName());
                echartDTO.setSjwc(sjwc/count+"");
                echartDTO.setJhwc(jhwc/count+"");
                list.add(echartDTO);
            }
        }
//        for(EchartDTO echartDTO:list){
//            System.out.println(echartDTO.getJdx()+"===="+echartDTO.getSjwc()+"====="+echartDTO.getJhwc());
//        }
        return list;
    }
    /**
     * XX公司对标提升工作月度报告---工作进度
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/groupReportMonth_gzjd" )
    public JSONObject groupReportMonth_gzjd(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        String spicFirstDeptId = httpServletRequest.getParameter("spicFirstDeptId");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String Month = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
            Month= month+"";
        }else{
            submitMonth = String.valueOf(month);
            Month = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        JSONObject jsonObject=new JSONObject();
        List<EchartDTO> no1=progressReportService.groupcompany_gztd_a(map);//第一段文本
        List<EchartDTO> no2=progressReportService.groupcompany_gztd_b(map);//第一段文本
        List<EchartDTO> no2_1=progressReportService.groupcompany_gztd_b_a(map);//第一段文本
        List<EchartDTO> no2_2=progressReportService.groupcompany_gztd_b_b(map);//第一段文本
        Double jhwc=Double.parseDouble(no1.get(0).getJhwc());
        Double sjwc=Double.parseDouble(no1.get(0).getSjwc());
        Double jhwcl=(Double.parseDouble(no1.get(0).getSjwc())/Double.parseDouble(no1.get(0).getJhwc()));
        DecimalFormat df = new DecimalFormat("0.00");
        String text1=sjwc>=jhwc?"超前":"滞后";
        jsonObject.put("text1","       集团公司对标提升行动包括战略管理、财务管理、客户与市场营销管理、运营管理、" +
                "科技管理、组织管理、人力资源管理、信息化管理、风险管理等九大对标专项，其中集团公司91项、九大专项120项、" +
                "60家二级单位2628项行动项。截止"+Month+"月底，集团公司对标提升工作计划完成的进度百分比为"+df.format(jhwc*100)
                +"%实际完成进度百分比为"+df.format(sjwc*100)+"%计划进度完成率"+df.format(jhwcl*100)+"%," +
                "整体工作进度"+text1);
        String text2="";
        List<ActionProejctDTO> actionProejctDTOS=actionProjectService.getAllAction();//全部的行动项
        List<EchartDTO> level1=new ArrayList<>();
        List<EchartDTO> level2=new ArrayList<>();
        List<EchartDTO> level3=new ArrayList<>();
        for(ActionProejctDTO actionProejctDTO:actionProejctDTOS){
            EchartDTO echartDTO=new EchartDTO();
            if(actionProejctDTO.getLevel().equals("1")){
                echartDTO.setActionid(actionProejctDTO.getId());
                level1.add(echartDTO);
            }
            if(actionProejctDTO.getLevel().equals("2")){
                echartDTO.setActionid(actionProejctDTO.getId());
                echartDTO.setParentid(actionProejctDTO.getParentProjectId());
                level2.add(echartDTO);
            }
            if(actionProejctDTO.getLevel().equals("3")){
                echartDTO.setActionid(actionProejctDTO.getId());
                echartDTO.setParentid(actionProejctDTO.getParentProjectId());
                level3.add(echartDTO);
            }
        }
        for(int i=0;i<no2.size();i++){
            if(i==no2.size()-1){
                text2+=no2.get(i).getJdx()+"("+df.format(Double.parseDouble(no2.get(i).getJhwcl())*100)+"%)。";
            }else{
                text2+=no2.get(i).getJdx()+"("+df.format(Double.parseDouble(no2.get(i).getJhwcl())*100)+"%)、";
            }
        }

        Integer l2NormalCount=0;//120项计数
        Integer l2OvdrdueCount=0;//120项计数
        for(EchartDTO echartDTO11:no2_1){
            String parentid[]=echartDTO11.getParentid().split(",");
            for(String str:parentid){
                for(EchartDTO echartDTO:level2){
                    if(str.equals(echartDTO.getActionid())){
                        if(Double.parseDouble(echartDTO11.getSjwc())>=Double.parseDouble(echartDTO11.getJhwc())){
                                l2NormalCount++;
                            }else{
                                l2OvdrdueCount++;
                            }
                    }
                }
            }

        }
        Integer l1NormalCount=0;//90项计数
        Integer l1OvdrdueCount=0;//90项计数
        for(EchartDTO l1:level1){
            for(EchartDTO l2:level2){//120项
                String l2parentid[]=l2.getParentid().split(",");
                for(String str:l2parentid){
                    if(str.equals(l1.getActionid())){
                        for(EchartDTO echartDTO:no2_1){
                            String parentid[]=echartDTO.getParentid().split(",");
                            for(String str1:parentid){
                                if(str1.equals(l2.getActionid())){
                                    if(Double.parseDouble(echartDTO.getSjwc())>=Double.parseDouble(echartDTO.getJhwc())){
                                        l1NormalCount++;
                                    }else{
                                        l1OvdrdueCount++;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Integer no2NormalCount=0;
        Integer no2OverdueCount=0;
        for(EchartDTO echartDTO:no2_2){
            echartDTO.setZongf(0.9*Double.parseDouble(echartDTO.getJhwc())+0.1*(Integer.parseInt(echartDTO.getXdxCount())-10)/(103-10));
            if(Double.parseDouble(echartDTO.getSjwc())>=Double.parseDouble(echartDTO.getJhwc())){
                no2NormalCount++;
            }else{
                no2OverdueCount++;
            }
        }
        String text3="";
        Collections.sort(no2_2, new Comparator<EchartDTO>()
        {
            public int compare(EchartDTO student1, EchartDTO student2)
            {
                return student2.getZongf().compareTo(student1.getZongf());
            }
        });
        Double a=no2OverdueCount+0.00;
        Double b=no2_2.size()+0.00;
        String compname_6=no2_2.get(0).getCompname()+"、"+no2_2.get(1).getCompname()+"、"+no2_2.get(2).getCompname()+"、"+no2_2.get(3).getCompname()+"、"+no2_2.get(4).getCompname()+"、"+no2_2.get(5).getCompname();
        String compname_3=no2_2.get(no2_2.size()-1).getCompname()+"、"+no2_2.get(no2_2.size()-2).getCompname()+"、"+no2_2.get(no2_2.size()-3).getCompname();
        jsonObject.put("text2","     集团公司对标提升行动九大专项计划进度完成率由高到低分别为"+text2+"集团公司91项行动项中，"+
                l2NormalCount+"项完成计划进度，"+l2OvdrdueCount+"项未完成计划进度,逾期行动项数量占比"+df.format((l2OvdrdueCount+0.0)/(l2OvdrdueCount+l2NormalCount+0.0))+"%。" +
                "九大专项120项行动项中，"+l1NormalCount+"项完成计划进度，"+l1OvdrdueCount+"项未完成计划进度，逾期行动项占比"+df.format((l1OvdrdueCount+0.0)/(l1OvdrdueCount+l1NormalCount+0.0))+"%。");
        jsonObject.put("text3","      "+no2_2.size()+"家二级单位，"+no2NormalCount+"家按期完成目标任务,"+no2OverdueCount+"家存在超期现象，" +
                "逾期二级单位占比"+(df.format(a/b*100))+"%。按工作清单任务数量占10%，任务完成率与时点目标比率占90%的加权平均排名，前6位分别是："+compname_6+"。后3位分别是"+compname_3);
        return jsonObject;
    }
    /**
     * XX公司对标提升工作月度报告---逾期项目
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/groupReportMonth_yuqiJdx" )
    public List<EchartDTO> groupReportMonth_yuqiJdx(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        String spicFirstDeptId = httpServletRequest.getParameter("spicFirstDeptId");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        Map<String,String> preMap = new HashMap<>();//查询上个月的填报数据
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        preMap.put("submitYear",submitYear);
        preMap.put("submitMonth",submitMonth);
        preMap.put("sjwc","1");
        preMap.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        List<SpecialProjectDTO> specialProjectDTOS = specialProjectService.getAllSpecialProList();
        List<EchartDTO> nineList=new ArrayList<EchartDTO>();
        List<EchartDTO> echartDTOS = progressReportService.yuqiJdx(map);//全部项目数据
        List<EchartDTO> yxEchartDTOS = progressReportService.yuqiJdx(preMap);//逾期进度项
        for(SpecialProjectDTO dto:specialProjectDTOS){
            int actionCount=0;
            int yuqiCount=0;
            EchartDTO progressReportDTO=new EchartDTO();
            for(EchartDTO echartDTO:echartDTOS){
                if(echartDTO.getJdxid().equals(dto.getId())){
                    actionCount++;
                }
            }
            for(EchartDTO echartDTO1:yxEchartDTOS){
                if(echartDTO1.getJdxid().equals(dto.getId())){
                    yuqiCount++;
                }
            }
            progressReportDTO.setActionCount(actionCount);
            progressReportDTO.setYuqiCount(yuqiCount);
            progressReportDTO.setNormalCount(actionCount-yuqiCount);
            progressReportDTO.setJdx(dto.getSpecialProjectName());
            nineList.add(progressReportDTO);
        }
//        for(EchartDTO dto:nineList){
//            System.out.println(dto.getJdx()+"==="+dto.getActionCount()+"===="+dto.getYuqiCount()+"===="+dto.getNormalCount());
//        }
        return nineList;
    }
    /**
     * XX公司对标提升工作月度报告---逾期项目---详细信息
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/yuqiJdx_xiangxi" )
    public List<EchartDTO> yuqiJdx_xiangxi(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        String spicFirstDeptId = httpServletRequest.getParameter("spicFirstDeptId");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        List<EchartDTO> echartDTOS = progressReportService.yuqiJdx_xiangxi(map);//全部项目数据
        DecimalFormat df=new DecimalFormat("0.00");
        for(EchartDTO dto:echartDTOS){
            dto.setSjwc(df.format(Double.parseDouble(dto.getSjwc()))+"%");
            dto.setJhwc(df.format(Double.parseDouble(dto.getJhwc()))+"%");
        }
        return echartDTOS;
    }
    /**
     * 集团公司对标提升工作月度报告（2月）-二级单位工作进展
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/ejdwjz_charts" )
    public List<EchartDTO> ejdwjz_charts(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String spicFirstDeptId = httpServletRequest.getParameter("spicFirstDeptId");
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        Map<String,String> map = new HashMap<>();
        Map<String,String> preMap = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("submitMonth",submitMonth);
        map.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));

        preMap.put("submitYear",submitYear);
        preMap.put("submitMonth",submitMonth);
        preMap.put("sjwc","1");
        preMap.put("endtime",subMonth(new SimpleDateFormat("yyyy-MM-dd").format(new Date())));
        List<EchartDTO> list=new ArrayList<>();
        JSONArray jsonArray=new JSONArray();
        List<EchartDTO> echartDTOList=progressReportService.ejdwjz_charts(map);
        List<EchartDTO> alljdx = progressReportService.yuqiJdx(map);//全部项目数据
        List<EchartDTO> yxEchartDTOS = progressReportService.yuqiJdx(preMap);//逾期进度项
        for(EchartDTO echartDTO:echartDTOList){
            //综合得分=（0.9*计划完成率+0.1*(X- Xmin)/(Xmax-Xmin)）,X二级单位细化行动项数量，Xmax为二级单位细化行动项数量最大值，Xmin为二级单位细化行动项数量最小值
            echartDTO.setJhwcl(Double.parseDouble(echartDTO.getSjwc())/Double.parseDouble(echartDTO.getJhwc())+"");
            echartDTO.setZongf(0.9*Double.parseDouble(echartDTO.getJhwc())+0.1*(Integer.parseInt(echartDTO.getXdxCount())-10)/(103-10));
            Integer normal=0;
            Integer overdue=0;
            for(EchartDTO all:alljdx){
                if(all.getNumber().equals(echartDTO.getNumber())){
                    normal++;
                }
            }
            for(EchartDTO yuqi:yxEchartDTOS){
                if(yuqi.getNumber().equals(echartDTO.getNumber())){
                    overdue++;
                }
            }
            echartDTO.setYuqiCount(overdue);
            echartDTO.setNormalCount(normal);

        }
        return echartDTOList;
    }
    /**
     * XX公司对标提升工作月度报告---原因分析，可编辑的信息
     * @param httpServletRequest
     * @return
     */
    @GetMapping(value = "/getReport" )
    public ReportDTO getReport(HttpServletRequest httpServletRequest) throws ParseException {
        Calendar cal = Calendar.getInstance();
        String spicFirstDeptId = httpServletRequest.getParameter("spicFirstDeptId");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submitMonth = null;
        String submitYear = String.valueOf(cal.get(Calendar.YEAR));
        EmployeeDTO employee = employeeService.getEmployeeById(getUserCode());
        Map<String,String> map = new HashMap<>();
        int month = cal.get(Calendar.MONTH);
        if(month<=9){
            submitMonth = "0"+month;
        }else{
            submitMonth = String.valueOf(month);
        }
        if(month==0){
            submitYear = String.valueOf(Integer.parseInt(submitYear)-1);
            submitMonth="12";
        }
        map.put("submitYear",submitYear);
        map.put("type","3");
        if(spicFirstDeptId!=null&&!spicFirstDeptId.equals(employee.getOrgCode())){//如果非当前部门查看报告，填写的数据必须审核通过后才能看到
            map.put("status","3");
        }
        map.put("submitMonth",submitMonth);
        map.put("deptid",spicFirstDeptId==null?employee.getOrgCode():spicFirstDeptId);
        ReportDTO reportDTO=reportService.getReportByCondition(map);
        reportDTO.setSubmitYear(submitYear);
        reportDTO.setSubmitMonth(submitMonth);
        reportDTO.setCompname(organizationService.getOrgNameByCode(employee.getOrgCode()));
//        System.out.println(reportDTO.getCompname());
        return reportDTO;
    }
    public static void main(String [] args) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String submityear="2021";
        String submitmonth="05";
        System.out.println(subMonth(submityear+"-"+submitmonth+"-30"));
    }
    /**

     * 获取两个日期相差的月数

     * @param d1 较大的日期

     * @param d2 较小的日期

     * @return 如果d1>d2返回 月数差 否则返回0

     */

    public static int getMonthDiff(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();

        Calendar c2 = Calendar.getInstance();

        c1.setTime(d1);

        c2.setTime(d2);

        if(c1.getTimeInMillis() < c2.getTimeInMillis()) return 0;

        int year1 = c1.get(Calendar.YEAR);

        int year2 = c2.get(Calendar.YEAR);

        int month1 = c1.get(Calendar.MONTH);

        int month2 = c2.get(Calendar.MONTH);

        int day1 = c1.get(Calendar.DAY_OF_MONTH);

        int day2 = c2.get(Calendar.DAY_OF_MONTH);

// 获取年的差值 假设 d1 = 2015-8-16 d2 = 2011-9-30

        int yearInterval = year1 - year2;

// 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数

        if(month1 < month2 || month1 == month2 && day1 < day2) yearInterval --;

// 获取月数差值

        int monthInterval = (month1 + 12) - month2 ;

        if(day1 < day2) monthInterval --;

        monthInterval %= 12;

        return yearInterval * 12 + monthInterval;

    }
}


